package com.kifas.sales.ui.tablemodel;

/**
 *
 * @author Kaiser
 * http://medan.nug.or.id/
 */

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;

public class DynamicTableModel<T> extends AbstractTableModel {
    private List<T> listData;
    private Class<T> className;
    private List<String> listFieldName = new ArrayList<String>();
    private List<String> listColumnName = new ArrayList<String>();

    public DynamicTableModel(List<T> listData, Class<T> className) {
        this.listData = listData;
        this.className = className;
    }

    public void addListColumnName(String columnName){
        this.listColumnName.add(columnName);
    }

    public void addListFieldName(String fieldName){
        this.listFieldName.add(fieldName);
    }
    
    public int getRowCount() {
        return listData.size();
    }

    public int getColumnCount() {
        return listColumnName.size();
    }

    @Override
    public String getColumnName(int column) {
        return listColumnName.get(column);
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        if (rowIndex<listData.size()){
            Method m;
            try {
                m = className.getMethod(listFieldName.get(columnIndex));
                return m.invoke(listData.get(rowIndex));
            } catch (IllegalAccessException ex) {
                Logger.getLogger(DynamicTableModel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(DynamicTableModel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InvocationTargetException ex) {
                Logger.getLogger(DynamicTableModel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchMethodException ex) {
                Logger.getLogger(DynamicTableModel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SecurityException ex) {
                Logger.getLogger(DynamicTableModel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        try {
            return className.getMethod(listFieldName.get(columnIndex)).getReturnType();
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(DynamicTableModel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(DynamicTableModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        return getValueAt(0, columnIndex).getClass();
    }
}
